var db = wx.cloud.database().collection('user');
Page({
  data: {
    loading: true,
    addressesList: [],
    openid: '',
    show:false
  },

  goEdit(event) {
    const id = event.target.dataset.addressId;
    wx.navigateTo({
      url: `../address-edit/address-edit?id=${id}`
    });
  },
  delete(e) {
    var that = this;
    const indexId = e.target.dataset.index;
    wx.showModal({
      title: '提示',
      content: '确定要删除这个收货地址吗?',
      success(res) {
        if (res.confirm) {
          var list = that.data.addressesList;
          var newArray = [];
          list.forEach(function (item, index, arr) {
            if (index != indexId) {
              newArray.push(list[index]);
            }
          });
          that.setData({
            addressesList:newArray
          });

          db.where({
            _openid: that.data.openid
          })
          .update({
            data: {
              userAddress: newArray
            }
          });


        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  setDefault(e) {
    var that = this;
    const checkedIndex = e.detail.value;
    var list = this.data.addressesList;
    list.forEach(function (item, index, arr) {
      if (index == checkedIndex) {
        arr[index].isDefault = true;
      } else {
        arr[index].isDefault = false;
      }
    });
    db.where({
        _openid: that.data.openid
      })
      .update({
        data: {
          userAddress: list
        }
      });

    wx.showToast({
      title: '设置成功!',
      icon: 'success'
    });
  },
  onLoad() {

    var that = this;
    wx.cloud.callFunction({
      name: 'login',
      success: res => {
        if (res.result.openid == undefined)
          return;
        that.setData({
          openid: res.result.openid
        });
        db.where({
            _openid: res.result.openid,
          })
          .get().then(r => {
            if (r.data.length >= 0) {
              that.setData({
                addressesList: r.data[0].userAddress
              });
              that.setData({
                show:true
              });
              this.loading = this.selectComponent("#loading");
              this.loading.HideLoading();
            }
          });

      },
      fail: res => {
        console.log(res);
      }
    });
 
  },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

});